"use client";

import React, { useEffect, useState } from "react";
import {
  Table,
  Button,
  Modal,
  Form,
  InputNumber,
  Switch,
  Input,
  message,
  Popconfirm,
  Space,
  Image,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  homeMediaControllerFindAll,
  homeMediaControllerCreate,
  homeMediaControllerUpdate,
  homeMediaControllerRemove,
} from "@/app/servers/api/homeMedia";
import { SingleUpload } from "@/app/components/single-upload/single-upload";

const HomeMediaPage: React.FC = () => {
  const [data, setData] = useState<API.ReturnHomeMediaDto[]>([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);


  const fetchData = async () => {
    try {
      setLoading(true);
      const response = await homeMediaControllerFindAll();
      setData(response.data);
    } catch {
      message.error("获取数据失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const handleAdd = () => {
    setEditingId(null);
    form.resetFields();
    setIsModalOpen(true);
  };

  const handleEdit = (record: API.ReturnHomeMediaDto) => {
    setEditingId(record.id);
    form.setFieldsValue({
      fileId: record.fileId,
      order: record.order,
      remark: record.remark,
      isDisplayed: record.isDisplayed,
      file: record.file,
    });
    setIsModalOpen(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await homeMediaControllerRemove({ id: id.toString() });
      message.success("删除成功");
      fetchData();
    } catch {
      message.error("删除失败");
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      const fileId = values.file.id;
      delete values.file;
      if (editingId) {
        await homeMediaControllerUpdate(
          { id: editingId.toString() },

          { ...values, fileId }
        );
        message.success("更新成功");
      } else {
        await homeMediaControllerCreate({
          ...values,
          fileId,
        });
        message.success("创建成功");
      }
      setIsModalOpen(false);
      fetchData();
    } catch {
      message.error("操作失败");
    }
  };

  const columns: ColumnsType<API.ReturnHomeMediaDto> = [
    {
      title: "预览图",
      key: "preview",
      render: (_, record) => (
        <Image
          src={record.file.href}
          alt={record.remark || "轮播图"}
          width={100}
          style={{ objectFit: "cover" }}
        />
      ),
    },
    {
      title: "文件ID",
      dataIndex: "fileId",
      key: "fileId",
    },
    {
      title: "排序",
      dataIndex: "order",
      key: "order",
      sorter: (a, b) => a.order - b.order,
    },
    {
      title: "备注",
      dataIndex: "remark",
      key: "remark",
    },
    {
      title: "是否展示",
      dataIndex: "isDisplayed",
      key: "isDisplayed",
      render: (isDisplayed: boolean) => (
        <Switch checked={isDisplayed} disabled />
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => handleDelete(record.id)}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="p-6">
      <div className="mb-4">
        <Button type="primary" onClick={handleAdd}>
          添加轮播图
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
      />

      <Modal
        title={editingId ? "编辑轮播图" : "添加轮播图"}
        open={isModalOpen}
        onOk={handleModalOk}
        onCancel={() => setIsModalOpen(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="file"
            label="轮播图"
            rules={[{ required: true, message: "请上传轮播图" }]}
          >
            <SingleUpload />
          </Form.Item>

          <Form.Item
            name="order"
            label="排序"
            rules={[{ required: true, message: "请输入排序序号" }]}
          >
            <InputNumber style={{ width: "100%" }} />
          </Form.Item>

          <Form.Item name="remark" label="备注">
            <Input.TextArea />
          </Form.Item>

          <Form.Item
            name="isDisplayed"
            label="是否展示"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default HomeMediaPage;
